import smtplib
import time
from email.header import Header
from email.mime.text import MIMEText
from email.utils import formataddr

from openpyxl import load_workbook
import os


def send_email(receivers, subject, content):
    sender = '543857523@qq.com'
    password = 'qqjjzkwhvwnybfci'  # 应该从环境变量或配置文件中获取
    try:
        # 创建 MIMEText 对象，指定邮件内容和 MIME 类型
        msg = MIMEText(content, 'plain', 'utf-8')
        # 设置邮件头部信息
        msg['From'] = formataddr(('工资条', sender))
        msg['Subject'] = Header(subject, 'utf-8')  # 使用 Header 以确保正确编码

        # 连接到 SMTP 服务器
        server = smtplib.SMTP_SSL('smtp.qq.com', 465)
        server.login(sender, password)

        # 设置邮件接收者，这里在循环外部设置
        msg['To'] = Header(''.join(receivers), 'utf-8')

        # 发送邮件
        server.sendmail(sender, receivers, msg.as_string())

        # 关闭服务器连接
        server.quit()
        return True
    except Exception as e:
        print('邮件发送失败，错误信息：', str(e))
        return False


file = os.path.join("data", "工资明细.xlsx")
wb = load_workbook(file)
sheet = wb.worksheets[0]

header_list = sheet[3]
header = []
for cell in header_list[3:]:
    header.append(cell.value)

for row in sheet.iter_rows(min_row=4):
    email = row[2].value
    row_data_list = []
    index = 0
    for cell in row[3:]:
        row_data_list.append([header[index], cell.value])
        index += 1
    # print(email, row_data_list)
    group_list = []
    for data_list in row_data_list:
        group = "{}:{}".format(data_list[0], data_list[1])
        group_list.append(group)
    email_string = " - ".join(group_list)
    # print(email, email_string)
    # print(email)
    send_email(email, "工资条", email_string)
    time.sleep(5)
